package com.coder.rental.utils;

import cn.hutool.core.codec.PunyCode;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author caelan
 * @project auto_rental
 */
@Component
public class JwtUtils {
    //JWT密钥
    public static final String SECRET_KEY = "caelan";
    //过期时间
    public static final long EXPIRE_TIME = 1000L*60*30;

    /**
     * 创建一个Token
     * @param payload
     * @return
     */
    public static String createToken(Map<String,Object> payload){
        DateTime now = DateTime.now();
        DateTime newTime = new DateTime(now.getTime()+EXPIRE_TIME);
        //设置Token的签发时间
        payload.put(JWTPayload.ISSUED_AT,now);
        //设置Token的过期时间
        payload.put(JWTPayload.EXPIRES_AT,newTime);
        //设置Token的生效时间，确保Token在签发后立即生效
        payload.put(JWTPayload.NOT_BEFORE,now);
        return JWTUtil.createToken(payload,SECRET_KEY.getBytes());
    }

    /**
     * 解析JWT Token并返回其Payload
     * @param token
     * @return
     */
    public static JWTPayload parseToken(String token){
        JWT jwt = JWTUtil.parseToken(token);    //解析传入的token字符串
        if (!jwt.setKey(SECRET_KEY.getBytes()).verify()){ // 验证token的签名，确保token未被篡改
            throw new RuntimeException("token异常");
        }
        if (!jwt.validate(0)){ // 检查token是否过期
            throw new RuntimeException("token已过期");
        }
        return jwt.getPayload(); // 返回token的payload部分
    }

/*    public static void main(String[] args) {
*//*        Map<String,Object> payload = new HashMap<>();
        payload.put("username","admin");
        payload.put("id","111");
        String token = createToken(payload);
        System.out.println(token);*//*
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE3NTI0Nzg4NzEsImlkIjoiMTExIiwiZXhwIjoxNzUyNDgwNjcxLCJpYXQiOjE3NTI0Nzg4NzEsInVzZXJuYW1lIjoiYWRtaW4ifQ.vicED6W_ZDiuKydRsO9ZaeRSzfEA2NK7Kr4L-5XOrnM";
        JWTPayload jwtPayload = parseToken(token);
        System.out.println(jwtPayload.getClaim("username"));
        System.out.println(jwtPayload.getClaim("id"));
    }*/
}
